package com.luck.easyfoodbatch.ui;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.custom.RoundedImageView;
import com.luck.easyfoodbatch.entity.Product;
import com.luck.easyfoodbatch.mvp.mine.EditGoods2Model;
import com.luck.easyfoodbatch.mvp.mine.EditGoods2Presenter;
import com.luck.easyfoodbatch.mvp.mine.EditGoods2View;
import com.luck.easyfoodbatch.mvp.mine.GoodsDetailModel;
import com.luck.easyfoodbatch.mvp.mine.GoodsDetailPresenter;
import com.luck.easyfoodbatch.mvp.mine.GoodsDetailView;
import com.luck.easyfoodbatch.mvp.mine.PublicGoods3Model;
import com.luck.easyfoodbatch.mvp.mine.PublicGoods3Presenter;
import com.luck.easyfoodbatch.mvp.mine.PublicGoods3View;
import com.luck.easyfoodbatch.mvp.mine.UploadImageModel;
import com.luck.easyfoodbatch.mvp.mine.UploadImageView;
import com.luck.easyfoodbatch.mvp.mine.UploadSinglePresenter;
import com.luck.easyfoodbatch.mvp.model.EditGoods;
import com.luck.easyfoodbatch.mvp.model.Goods3Model;
import com.luck.easyfoodbatch.mvp.model.GoodsDetail;
import com.luck.easyfoodbatch.mvp.model.UploadModel;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.Tools;
import com.luck.picture.lib.model.FunctionConfig;
import com.luck.picture.lib.model.PictureConfig;
import com.yalantis.ucrop.entity.LocalMedia;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class UploadCertificateActivity extends BaseActivity implements UploadImageView, PublicGoods3View, EditGoods2View, GoodsDetailView {

    @BindView(R.id.riv_permit)
    RoundedImageView rivPermit;
    @BindView(R.id.rl_permit)
    RelativeLayout rlPermit;
    @BindView(R.id.riv_pass)
    RoundedImageView rivPass;
    @BindView(R.id.rl_pass)
    RelativeLayout rlPass;
    @BindView(R.id.riv_tax)
    RoundedImageView rivTax;
    @BindView(R.id.rl_tax)
    RelativeLayout rlTax;
    @BindView(R.id.riv_hygiene)
    RoundedImageView rivHygiene;
    @BindView(R.id.rl_hygiene)
    RelativeLayout rlHygiene;
    @BindView(R.id.btn_next_graphic)
    Button btnNextGraphic;
    @BindView(R.id.tv_line1)
    TextView tv_line1;
    @BindView(R.id.tv_line2)
    TextView tv_line2;
    @BindView(R.id.tv_line3)
    TextView tv_line3;
    @BindView(R.id.tv_line4)
    TextView tv_line4;
    private Product product;
    private UploadImageModel imageModel;
    private PublicGoods3Model goods3Model;
    private List<LocalMedia> photoInfos = new ArrayList<>();
    private int type = 0;// 0商品流通许可证 1过关证 2税单 3卫生检测证明
    private int flag = 0;
    private String title = "", gid = "", license_path = "", pass_customs_path = "", bill_path = "", health_detection_path = "";
    private EditGoods2Model goods2Model;
    private GoodsDetailModel detailModel;
    private boolean isUpload = false;
    private int product_type = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        flag = getIntent().getIntExtra("type", 0);
        //国产传第一项 进口传下面三项
        if (flag == 1) {
            title = "编辑商品(认证证书)";
            gid = getIntent().getStringExtra("gid");

        } else {
            title = "上传商品(认证证书)";
        }
        setContentView(R.layout.activity_upload_certificate, title, MODE_BACK_NAVIGATION);
        ButterKnife.bind(this);
        product_type = getIntent().getIntExtra("product_type", 0);
        // 产品类型1国产2进口
        if (product_type == 1) {
            rlPermit.setVisibility(View.VISIBLE);
            rlPass.setVisibility(View.GONE);
            rlTax.setVisibility(View.GONE);
            rlHygiene.setVisibility(View.GONE);
            tv_line1.setVisibility(View.VISIBLE);
            tv_line2.setVisibility(View.GONE);
            tv_line3.setVisibility(View.GONE);
            tv_line4.setVisibility(View.GONE);
        } else if (product_type == 2) {
            rlPermit.setVisibility(View.GONE);
            rlPass.setVisibility(View.VISIBLE);
            rlTax.setVisibility(View.VISIBLE);
            rlHygiene.setVisibility(View.VISIBLE);
            tv_line1.setVisibility(View.GONE);
            tv_line2.setVisibility(View.VISIBLE);
            tv_line3.setVisibility(View.VISIBLE);
            tv_line4.setVisibility(View.VISIBLE);
        }

        product = (Product) getIntent().getSerializableExtra("product");
        if (flag == 1) {
            // 编辑状态
            btnNextGraphic.setText("保存");
            detailModel = new GoodsDetailPresenter(this, mContext);
            showProgressDialog(getString(R.string.app_loading));
            detailModel.requestGoodsDetail(gid);
        }
    }

    @Override
    public void backClick() {
        setResult(RESULT_OK);
        finish();
        super.backClick();
    }

    @OnClick({R.id.rl_permit, R.id.rl_pass, R.id.rl_tax, R.id.rl_hygiene, R.id.btn_next_graphic})
    public void onClick(View view) {
        FunctionConfig options = new FunctionConfig();
        options.setCompress(true);
        options.setSelectMode(FunctionConfig.MODE_SINGLE);
        PictureConfig.init(options);
        switch (view.getId()) {
            case R.id.rl_permit:
                // 商品流通许可证
                type = 0;
                PictureConfig.getPictureConfig().openPhoto(UploadCertificateActivity.this,resultCallback);
                break;
            case R.id.rl_pass:
                // 过关证
                type = 1;
                PictureConfig.getPictureConfig().openPhoto(UploadCertificateActivity.this,resultCallback);
                break;
            case R.id.rl_tax:
                // 税单
                type = 2;
                PictureConfig.getPictureConfig().openPhoto(UploadCertificateActivity.this,resultCallback);
                break;
            case R.id.rl_hygiene:
                // 卫生检测证明
                type = 3;
                PictureConfig.getPictureConfig().openPhoto(UploadCertificateActivity.this,resultCallback);
                break;
            case R.id.btn_next_graphic:
                // 产品类型1国产2进口
                if (!Tools.isNull(product_type)) {
                    if (product_type == 1) {
                        if (Tools.isNull(license_path)) {
                            T.showToast(mContext, "请上传商品流通许可证~");
                            return;
                        }

                    } else if (product_type == 2) {
                        if (Tools.isNull(pass_customs_path)) {
                            T.showToast(mContext, "请上传过关单~");
                            return;
                        } else if (Tools.isNull(bill_path)) {
                            T.showToast(mContext, "请上传过税单~");
                            return;
                        } else if (Tools.isNull(health_detection_path)) {
                            T.showToast(mContext, "请上传卫生简测证明~");
                            return;
                        }
                    }
                }

                if (flag == 1) {
                    if (!isUpload) {
                        // 如果没动过图片不做处理
                        finish();
                        return;
                    }
                    // 编辑状态
                    if (product == null) {
                        product = new Product();
                    }
                    product.setGid(gid);
                    product.setLicense_path(license_path);
                    product.setPass_customs_path(pass_customs_path);
                    product.setBill_path(bill_path);
                    product.setHealth_detection_path(health_detection_path);
                    showProgressDialog(getString(R.string.app_loading));
                    goods2Model = new EditGoods2Presenter(this, mContext);
                    goods2Model.requestEditGoods(2, product);
                } else {
                    if (product != null) {
                        showProgressDialog(getString(R.string.app_loading));
                        goods3Model = new PublicGoods3Presenter(this, mContext);
                        goods3Model.uploadGoods(product);
                    }
                }
                break;
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                setResult(RESULT_OK);
                finish();
                return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void publicGoods3Success(Goods3Model model) {
        if (model.getStatus() == HttpUtil.RESULT_OK) {
            setResult(RESULT_OK);
            finish();
            T.showToast(mContext, model.getMsg());
        } else {
            T.showToast(mContext, model.getMsg());
        }
    }

    @Override
    public void uploadSuccess(UploadModel model) {
        if (model.getStatus() == HttpUtil.RESULT_OK) {
            List<String> data = model.getData();
            if (product == null) {
                product = new Product();
            }
            if (data != null && data.size() > 0) {
                switch (type) {
                    case 0:
                        license_path = data.get(0);
                        product.setLicense_path(license_path);
                        break;
                    case 1:
                        pass_customs_path = data.get(0);
                        product.setPass_customs_path(pass_customs_path);
                        break;
                    case 2:
                        bill_path = data.get(0);
                        product.setBill_path(bill_path);
                        break;
                    case 3:
                        health_detection_path = data.get(0);
                        product.setHealth_detection_path(health_detection_path);
                        break;
                }
            }
        } else {
            T.showToast(mContext, model.getMsg());
        }
    }

    @Override
    public void editGoods2Success(EditGoods model) {
        if (model != null && model.getStatus() == HttpUtil.RESULT_OK) {
            setResult(RESULT_OK);
            finish();
        }
    }

    @Override
    public void getGoodsDetailSuccess(GoodsDetail model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                GoodsDetail.DataBean modelData = model.getData();
                if (modelData != null) {
                    license_path = modelData.getLicense_path();
                    pass_customs_path = modelData.getPass_customs_path();
                    bill_path = modelData.getBill_path();
                    health_detection_path = modelData.getHealth_detection_path();
                    if (!Tools.isNull(license_path)) {
                        Glide.with(getApplicationContext())
                                .load(HttpUtil.IMG_BASE_URL + license_path)
                                .centerCrop()
                                .diskCacheStrategy(DiskCacheStrategy.ALL)
                                .into(rivPermit);
                    } else {
                        rivPermit.setImageResource(R.mipmap.camera);
                    }
                    if (!Tools.isNull(pass_customs_path)) {
                        Glide.with(getApplicationContext())
                                .load(HttpUtil.IMG_BASE_URL + pass_customs_path)
                                .centerCrop()
                                .diskCacheStrategy(DiskCacheStrategy.ALL)
                                .into(rivPass);
                    } else {
                        rivPass.setImageResource(R.mipmap.camera);
                    }
                    if (!Tools.isNull(bill_path)) {
                        Glide.with(getApplicationContext())
                                .load(HttpUtil.IMG_BASE_URL + bill_path)
                                .centerCrop()
                                .diskCacheStrategy(DiskCacheStrategy.ALL)
                                .into(rivTax);
                    } else {
                        rivTax.setImageResource(R.mipmap.camera);
                    }
                    if (!Tools.isNull(health_detection_path)) {
                        Glide.with(getApplicationContext())
                                .load(HttpUtil.IMG_BASE_URL + health_detection_path)
                                .centerCrop()
                                .diskCacheStrategy(DiskCacheStrategy.ALL)
                                .into(rivHygiene);
                    } else {
                        rivHygiene.setImageResource(R.mipmap.camera);
                    }
                }
            }
        }
    }

    @Override
    public void httpStatusError() {
        T.showToast(mContext, getString(R.string.app_http_error));
    }

    @Override
    public void hideLoading() {
        hideShowProgress();
    }

    @Override
    public void upProgress(long currentSize, long totalSize, float progress, long networkSpeed) {

    }


    private PictureConfig.OnSelectResultCallback resultCallback = new PictureConfig.OnSelectResultCallback() {
        @Override
        public void onSelectSuccess(List<LocalMedia> list) {
            photoInfos = list;
            if (photoInfos != null || photoInfos.size() > 0) {
                showProgressDialog("正在上传，请稍候……");
                LocalMedia media = photoInfos.get(0);
                File file;
                if (media.isCompressed()) {
                    file = new File(media.getCompressPath());
                } else {
                    file = new File(media.getPath());
                }
                isUpload = true;
                RoundedImageView imageView = null;
                switch (type) {
                    case 0:
                        imageView = rivPermit;
                        break;
                    case 1:
                        imageView = rivPass;
                        break;
                    case 2:
                        imageView = rivTax;
                        break;
                    case 3:
                        imageView = rivHygiene;
                        break;
                }
                Glide.with(getApplicationContext())
                        .load(file)
                        .asBitmap().centerCrop()
                        .placeholder(R.mipmap.camera)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .into(imageView);
                imageModel = new UploadSinglePresenter(UploadCertificateActivity.this, mContext);
                imageModel.uploads(0, file, null);
            }
        }
    };
}
